# encoding:utf8

from ccpm.collogger import Log
import sys
import json
import os
from ccpm.constants import Constant
from mgamedev.py_lib.decorator import singleton     # noqa
from mgamedev.py_lib.luabase import LuabaseTool  # noqa

HOOKS_FILEMAP = dict(
    publish_pre_zip="publish_pre_zip"
)


@singleton
class HookFunc(LuabaseTool):
    def __init__(self):
        super().__init__()
        self.hook_path = Constant.HOOKS_PATH

    def get_hookf(self, fname):
        relstatic = os.path.relpath(
            Constant.HOOKS_PATH, Constant.INSTALL_PATH)
        # debug
        static_f = os.path.join(os.getcwd(), os.path.join(relstatic, fname))
        if os.path.isfile(static_f):
            return static_f
        else:
            return os.path.join(self.hook_path, fname)

    def set_hookpath(self, path):
        self.hook_path = path

    def chk_runable(self, hookf):
        if hookf not in HOOKS_FILEMAP:
            Log().error("[hookfunc]not find the hookfunc name = %s", hookf)
            return
        hooktar = self.get_hookf(HOOKS_FILEMAP[hookf])
        if os.path.isfile(hooktar):
            os.system("chmod a+x %s" % hooktar)
            return hooktar

    def hook_exe(self, isignore, hookf, *argv):
        if isignore:
            return
        hooktar = self.chk_runable(hookf)
        if hooktar:
            Log().info("[hookfunc]execute the hookfunc %s", hooktar)
            os.system("%s %s" % (hooktar, " ".join(argv)))
